from copy import deepcopy
from app.product.category.model import Category as CategoryTable
from app.product.category import dao
from common.mixins import DictMixin
from common.utils.utils import custom_marshal_pagination, custom_marshal_list
from common.utils.pinyin import get_first_letter_pinyin
from exts import db


# ------------- route ------------
# def create(user_id, **kwargs):
#     if not kwargs.get('short_name'):
#         kwargs['short_name'] = get_first_letter_pinyin(kwargs.get("name"))
#     new_obj = DictMixin.from_dict(CategoryTable, kwargs)
#     new_obj.creator_id = user_id
#     db.session.add(new_obj)
#     db.session.commit()
#     return new_obj


# def get_by_page(user_id, **kwargs):
#     pagination = dao.get_by_page(**kwargs)
#     pagination = custom_marshal_pagination(pagination)
#     return pagination


def get_all(user_id, **kwargs):
    # 把 parent_name 加进去
    all_category = custom_marshal_list(dao.get_all(**kwargs))
    new_all_category = []
    for category in all_category:
        new_category = CategoryTable.query.filter_by(id=category['id']).first()
        new_all_category.append(new_category)
        new_category.parent = CategoryTable.query.filter_by(id=category['parent_id']).first()
    return new_all_category


# def get(user_id, obj_id):
#     return CategoryTable.query.filter_by(id=obj_id).first()


# def _update(user_id, obj_id, **kwargs):
#     obj = CategoryTable.query.filter_by(id=obj_id).first()
#     old_obj = deepcopy(obj)
#     new_obj = DictMixin.from_dict(obj, kwargs)
#     new_obj.updater_id = user_id
#     # 当名称发生修改时，自动更新short_name
#     if new_obj.name and old_obj.name != new_obj.name:
#         new_obj.short_name = get_first_letter_pinyin(new_obj.name)
#     return new_obj
#
#
# def update(user_id, obj_id, **kwargs):
#     new_obj = _update(user_id, obj_id, **kwargs)
#     db.session.commit()
#     return new_obj


# def delete(user_id, obj_id):
#     obj = CategoryTable.query.filter_by(id=obj_id).first()
#     db.session.delete(obj)
#     db.session.commit()
#     return obj.id
#
#
# def delete_many(user_id, obj_ids_list):
#     objs = CategoryTable.query.filter(CategoryTable.id.in_(obj_ids_list)).all()
#     [db.session.delete(u) for u in objs]
#     db.session.commit()
#     return obj_ids_list

# help

def category_list_to_tree_dict(category_list):
    # 父节点还未遍历，先遍历了子节点
    root = []
    lookup = {}
    for category in category_list:
        category['key'] = category['id']
        category['title'] = category['name']
        category['value'] = category['id']

        if category["parent_id"] is None:
            root.append(category)
            lookup[category["id"]] = category
        else:
            node = category
            # 判断能否找到父
            if category["parent_id"] in lookup.keys():
                lookup[category["parent_id"]].setdefault('children', []).append(node)
                lookup[category["id"]] = node
            else:
                print("parent_id", category["parent_id"])
                print("lookup", lookup.keys())
    return root


# def category_list_to_tree_dict(category_list):
#     if len(category_list) == 0:
#         return []
#     root = []
#     lookup = {}
#     list_to_tree_recursive(root, lookup, category_list)
#     return root


def list_to_tree_recursive(root, lookup, category_list):
    # 当确实没有父的时候，无法结束循环
    if len(category_list) == 0:
        return

    rest_category_list = []
    for category in category_list:
        category['key'] = category['id']
        category['title'] = category['name']
        category['value'] = category['id']

        if category["parent_id"] is None:
            root.append(category)
            lookup[category["id"]] = category
        else:
            node = category
            # 判断能否找到父
            if category["parent_id"] in lookup.keys():
                lookup[category["parent_id"]].setdefault('children', []).append(node)
                lookup[category["id"]] = node
            else:
                rest_category_list.append(node)
    return list_to_tree_recursive(root, lookup, rest_category_list)


# def batch_update(user_id, obj_ids_list, **kwargs):
#     for obj_id in obj_ids_list:
#         _update(user_id, obj_id, **kwargs)
#     db.session.commit()
#     return obj_ids_list
